package org.jsbd.boss.security;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.jsbd.boss.domian.User;
import org.jsbd.boss.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;


public class MonitorRealm extends AuthorizingRealm {

  private static final Logger logger = LoggerFactory.getLogger(MonitorRealm.class);
  @Autowired
  private IUserService        userService;

  public MonitorRealm() {
    super();

  }

  /**
   * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
   */
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    return new SimpleAuthorizationInfo();
  }

  /**
   * 认证回调函数,登录时调用
   */
  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
    UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
    User form = new User();
    form.setUserName(token.getUsername());
    User currentUser = null;
    try {
      currentUser = userService.findUser(form);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      throw new AuthenticationException();
    }
    if (currentUser == null) {
      throw new AuthenticationException();
    }
    return new SimpleAuthenticationInfo(currentUser.getUserName(), currentUser.getPassword(), getName());
  }

  /**
   * 更新用户授权信息缓存
   * 
   * @param principal
   */
  public void clearCachedAuthorizationInfo(String principal) {
    SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
    clearCachedAuthorizationInfo(principals);
  }

  /**
   * 清除所有用户授权信息缓存.
   */
  public void clearAllCachedAuthorizationInfo() {
    Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
    if (cache != null) {
      for (Object key : cache.keys()) {
        cache.remove(key);
      }
    }
  }

}
